import { Input } from 'antd';
import type { InputRef } from 'antd';
import type { FC } from 'react';
import { useRef, useState } from 'react';
import iconSrc from './icon.png';
import styles from './index.less';

interface Props {
  value: string;
  onChange: (val: string) => void;
  maxWidth?: number;
}
const Index: FC<Props> = ({ value, onChange, maxWidth }) => {
  const [input, setInput] = useState(false);
  const inputRef = useRef<InputRef>();

  return (
    <div className={styles.container}>
      {input ? (
        <Input
          defaultValue={value}
          ref={inputRef as any}
          onBlur={(evt) => {
            onChange?.(evt.target.value);
            setInput(false);
          }}
        />
      ) : value ? (
        <span
          style={{ width: maxWidth }}
          onClick={() => {
            setInput(true);
            setTimeout(() => {
              inputRef.current?.focus();
            }, 0);
          }}
        >
          {value}
          <sup>
            <img loading="lazy" style={{ width: 14 }} src={iconSrc} alt="" />
          </sup>
        </span>
      ) : (
        <Input
          placeholder="请输入章节名字"
          onFocus={() => {
            setInput(true);
            setTimeout(() => {
              inputRef.current?.focus();
            }, 0);
          }}
        />
      )}
    </div>
  );
};

export default Index;
